package top.xchch.tool.cipher.atguigu;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class KeyGenerate08 {
    public static void main(String[] args) throws Exception {
        String algorithm = "RSA";
        String keyDir = "./src/main/resources/key/";
        String aPubPath = keyDir + "a.pub";
        String aPriPath = keyDir + "a.pri";
//        创建密钥对
        generateKeyToFile(algorithm, aPubPath, aPriPath);
//        // 读取私钥key
        PrivateKey privateKey = getPrivateKey(aPriPath, algorithm);
//        // 读取公钥key
        PublicKey publicKey = getPublicKey(aPubPath, algorithm);
    }

    /**
     * 读取私钥
     */
    public static PrivateKey getPrivateKey(String priPath, String algorithm) throws Exception{
        String privateKeyString = FileUtils.readFileToString(new File(priPath), Charset.defaultCharset());
        // 创建key的工厂
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        // 创建私钥key的规则
        PKCS8EncodedKeySpec privateKey = new PKCS8EncodedKeySpec(Base64.decode(privateKeyString));
        // 返回私钥对象
        return keyFactory.generatePrivate(privateKey);
    }

    /**
     * 读取私钥
     */
    public static PublicKey getPublicKey(String pubPath, String algorithm) throws Exception{
        String privateKeyString = FileUtils.readFileToString(new File(pubPath), Charset.defaultCharset());
        // 创建key的工厂
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        // 创建公钥key的规则
        X509EncodedKeySpec publicKey = new X509EncodedKeySpec(Base64.decode(privateKeyString));
        // 返回公钥对象
        return keyFactory.generatePublic(publicKey);
    }

    /**
     * 保存公钥和私钥
     */
    private static void generateKeyToFile(String algorithm, String pubPath, String priPath) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // 生成密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 生成公钥
        PublicKey publicKey = keyPair.getPublic();
        // 生成私钥
        PrivateKey privateKey = keyPair.getPrivate();
        // 获取公钥的字节数组
        byte[] publicKeyEncoded = publicKey.getEncoded();
        // 获取私钥的字节数组
        byte[] privateKeyEncoded = privateKey.getEncoded();
        // 使用base64进行编码
        String publicEncodeString = Base64.encode(publicKeyEncoded);
        String privateEncodeString = Base64.encode(privateKeyEncoded);
        // 把公钥和私钥保存到根目录
        FileUtils.writeStringToFile(new File(pubPath), publicEncodeString, Charset.forName("UTF-8"));
        FileUtils.writeStringToFile(new File(priPath), privateEncodeString, Charset.forName("UTF-8"));
    }
}
